package com.kl.daojishiii;

import android.annotation.TargetApi;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class JobSchedulerUtil {
    private static final int JOB_ID = 1;
    private static JobSchedulerUtil mJobUtil;
    private Context mContext;
    private JobScheduler mJobScheduler;

    private JobSchedulerUtil(Context ctxt) {
        mContext = ctxt;
        mJobScheduler = (JobScheduler) ctxt.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    }

    public static JobSchedulerUtil getJobSchedulerInstance(Context ctxt) {
        if (mJobUtil == null) {
            mJobUtil = new JobSchedulerUtil(ctxt);
        }
        return mJobUtil;
    }

    @TargetApi(21)
    public void startJobScheduler() {
        // 如果JobService已经启动,取消之前的job
        if (JobSchedulerService.isJobServiceAlive()) {
            stopJobScheduler();
        }

        // 构建JobInfo对象，传递给JobSchedulerService
        JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, new ComponentName(mContext, JobSchedulerService.class));
        //android7.0 及以上系统
        if (Build.VERSION.SDK_INT >= 24) {
            builder.setMinimumLatency(3000); //至少3s 才会执行
            builder.setOverrideDeadline(3000); //3s后一定会执行
            builder.setMinimumLatency(3000);
//            //默认是10s，如果小于10s，也会按照10s来依次增加
//            builder.setBackoffCriteria(10000, JobInfo.BACKOFF_POLICY_LINEAR);
        } else {
            builder.setPeriodic(3000);
        }
        // 当插入充电器，执行该任务
        builder.setRequiresCharging(true);
        JobInfo info = builder.build();
        //开始定时执行该系统任务
        mJobScheduler.schedule(info);
    }

    public void stopJobScheduler() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mJobScheduler.cancel(JOB_ID);
        }
    }
}